package com.ltmonitor.web.controller;

import com.ltmonitor.service.IVideoStreamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Controller
@RequestMapping("risk")
public class RiskAction extends GenericAction{
	@Autowired
	private IVideoStreamService videoStreamService;

	@RequestMapping("/viewChart.action")
	public String viewChart(String chartType,Model m) {
		m.addAttribute("chartType", chartType);
		return "/risk/riskRecognizeChart";
	}

	@RequestMapping(value = "/{plateNo}.{plateColor}.{channel}.{video}.{authorizeCode}")
	public void index(@PathVariable String plateNo,
					  @PathVariable int plateColor,
					  @PathVariable int channel,
					  @PathVariable int video,
					  @PathVariable String authorizeCode,
					  HttpServletRequest request, HttpServletResponse response
					  ) {

		String name = plateNo + "," + plateColor + "," + channel;

		List<byte[]> data = this.videoStreamService.getPackets();
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			String line;
			try {
				int index = 0;
				while(index < data.size())
				{
					byte[] b = data.get(index);
					out.write(b, 0, b.length);
					index++;
					if(index == data.size())
						index = 0;

					Thread.sleep(20);
				}

			} catch (Exception e) {
				log.error(e.getMessage(),e);
			}

		} catch (Exception e) {
			System.out.println("文件流输出异常");
			log.error(e.getMessage(),e);
		}
		finally {
			try {
				if(out != null)
				out.close();
			} catch (IOException e) {
				System.out.println("文件流关闭异常");
				log.error(e.getMessage(),e);
			}
		}

	}
	public static byte[] HexString2Bytes(String hexstr) {
		byte[] b = new byte[hexstr.length() / 2];
		int j = 0;

		for (int i = 0; i < b.length; i++) {
			char c0 = hexstr.charAt(j++);
			char c1 = hexstr.charAt(j++);

			b[i] = ((byte) (parse(c0) << 4 | parse(c1)));
			//int start = i * 2;
			//int c = Integer.parseInt(hexstr.substring(start, start + 2));
			//b[i] = (byte)c;
		}

		return b;
	}

	private static int parse(char c) {
		if (c >= 'a') {
			return c - 'a' + 10 & 0xF;
		}

		if (c >= 'A') {
			return c - 'A' + 10 & 0xF;
		}

		return c - '0' & 0xF;
	}
}
